<template>
  <view class="shoppingCart">
    <view v-if="token || userInfo.uid">
      <view v-if="validList.length > 0">
        <view class="nav acea-row row-between-wrapper" style="position: static; background-color: transparent; border: none">
          <view v-if="validList?.length > 0" class="administrate acea-row row-center-wrapper" @click="manage" style="text-align: right; margin-left: auto; border: none; min-width: 114rpx; height: 40rpx; background: #ffffff; padding: 0 68rpx; border-radius: 24rpx 24rpx 24rpx 24rpx; white-space: nowrap"> {{ footerswitch ? '退出管理' : '管理' }}</view>
        </view>
        <view class="list">
          <view class="item acea-row row-between-wrapper" v-for="(itPar, designIndex) in validList" :key="designIndex">
            <div class="design-item">
              <view class="design-item-pic" @click="goDesignCon(itPar)">
                <image class="deign-pic" :src="itPar.designerAvatar" />
                <div class="desgin-name">{{ itPar.designerName }}</div>
                <image class="right-icon" src="https://cos.aitshirt.cn/app-icon/rightarr.png"></image>
              </view>
              <div v-for="(item, cartIndex) in itPar.catList" :key="cartIndex" class="cart-_item" style="">
                <view class="select-btn">
                  <view class="checkbox-wrapper">
                    <checkbox-group @change="switchSelect(designIndex, cartIndex)">
                      <label class="well-check">
                        <checkbox color="#eb3729" value :checked="item.checked"></checkbox>
                      </label>
                    </checkbox-group>
                  </view>
                </view>
                <view class="picTxt acea-row row-between-wrapper" style="flex-wrap: nowrap; width: auto">
                  <view class="pictrue" @click="goGoodsCon(item)">
                    <image :src="item.productInfo?.attrInfo?.image" v-if="item.productInfo?.attrInfo && item.productInfo?.attrInfo?.image"  mode="aspectFit"/>
                    <image :src="item.productInfo?.image" v-else mode="aspectFit"/>
                  </view>
                  <view class="text">
                    <view class="line1">{{ item.productInfo?.storeName }}</view>
                    <view class="infor line1" v-if="item.productInfo?.attrInfo">已选：{{ item.productInfo?.attrInfo.sku }}</view>
                    <view class="money" style="color: #f25a27; font-size: 32rpx; font-weight: bold">￥{{ item.truePrice }}</view>
                  </view>
                  <view class="carnum acea-row row-center-wrapper">
                    <view class="reduce" :class="validList[designIndex].catList[cartIndex].cartNum <= 1 ? 'on' : ''" @click.prevent="reduce(designIndex, cartIndex)">-</view>
                    <view class="num">{{ item.cartNum }}</view>
                    <view class="plus" v-if="validList[designIndex].catList[cartIndex].attrInfo" :class="validList[designIndex].catList[cartIndex].cartNum >= validList[designIndex].catList[cartIndex].attrInfo.stock ? 'on' : ''" @click.prevent="plus(cartListValidIndex)">+</view>
                    <view class="plus" v-else :class="validList[designIndex].catList[cartIndex].cartNum >= validList[designIndex].catList[cartIndex].stock ? 'on' : ''" @click.prevent="plus(designIndex, cartIndex)">+</view>
                  </view>
                </view>
              </div>
            </div>
          </view>
        </view>
      </view>
      <!--购物车暂无商品-->
      <view class="noCart" v-if="cartList.valid.length === 0 && cartList.invalid.length === 0">
        <view class="pictrue">
          <image :src="`https://cos.aitshirt.cn/app-icon/%E7%BB%84%2014%402x.png`" />
        </view>
        <!--        <Recommend></Recommend>-->
      </view>
      <view style="height: 210rpx"></view>
      <view :class="{ 'footer acea-row row-between-wrapper': true, 'footer-h5': isH5 }" v-if="cartList.valid.length > 0">
        <view>
          <view class="select-btn">
            <view class="checkbox-wrapper">
              <!-- <label class="well-check">
              <input
                type="checkbox"
                name
                value
                :checked="isAllSelect && cartCount > 0"
                @click="allChecked"
              />
              <i class="icon"></i>
              <text class="checkAll">全选 ({{ cartCount }})</text>
              </label>-->

              <checkbox-group @change="allChecked">
                <label class="well-check">
                  <checkbox color="#eb3729" value="allSelect" :checked="isAllSelect && cartCount > 0"></checkbox>
                  <text class="checkAll">全选 ({{ cartCount }})</text>
                </label>
              </checkbox-group>
            </view>
          </view>
        </view>
        <view class="money acea-row row-middle" v-if="footerswitch === false">
          <text class="font-color-red">￥{{ countmoney }}</text>
          <view class="placeOrder bg-color-red" @click="placeOrder">立即下单</view>
        </view>
        <view class="button acea-row row-middle" v-else>
          <!-- <view class="bnt cart-color" @click="collectAll">收藏</view> -->
          <view class="bnt" @click="delgoods">删除</view>
        </view>
      </view>
    </view>
    <Authorization v-else ref="authorization" />
  </view>
</template>
<script>
// import Recommend from "@/components/Recommend";
import Authorization from '@/pages/login/index';
const userStore = useAuthStore();

import { getCartList, postCartDel, changeCartNum, getCartCount } from '@/api/store';
import { postCollectAll } from '@/api/user';
import { mul, add } from '@/utils/bc';
import cookie from '@/utils/store/cookie';
import { useAuthStore } from '@/state/modules/user';
import { _router } from '@/utils/oldIndex';

const CHECKED_IDS = 'cart_checked';

export default {
  name: 'ShoppingCart',
  components: {
    // Recommend,
    Authorization,
  },
  props: {},
  data: function () {
    return {
      cartList: {
        invalid: [],
        valid: [],
      },
      isH5: false,
      validDesignList: [],
      validList: [],
      isAllSelect: false,
      cartCount: 0,
      countmoney: 0,
      goodsHidden: true,
      footerswitch: false,
      count: 0,
      checkedIds: [],
      loaded: false,
    };
  },
  computed: {
    // mapGetters(["userInfo", "token"])
    userInfo: function () {
      return userStore.user;
    },
    token: function () {
      return userStore.token;
    },
  },
  //   watch: {
  //     $yroute(n) {
  //       if (n.name === "ShoppingCart") {
  //         this.carnum();
  //         this.countMoney();
  //         this.getCartList();
  //         this.gainCount();
  //         this.goodsHidden = true;
  //         this.footerswitch = false;
  //       }
  //     },
  //     cartList(list) {
  //       this.validList = list.valid;
  //     }
  //   },
  onLoad() {
    // if (wx.getUserProfile) {
    //   this.canIUseGetUserProfile = true
    // }
    if (!userStore.token && !userStore.user?.uid) {
      this.$refs.authorization.getLoginCode();
    }
  },
  watch: {
    userInfo(user) {
      if (user.uid) {
        this.carnum();
        this.countMoney();
        this.getCartList();
        this.gainCount();
      }
    },
    token(token) {
      if (this.userInfo.uid) {
        this.carnum();
        this.countMoney();
        this.getCartList();
        this.gainCount();
      }
    },
    cartList(list) {
      this.validList = list.valid;
    },
  },
  onShow: function () {
    // #ifdef H5
    this.isH5 = true;
    // #endif
    console.log(this.userInfo);
    if (this.userInfo.uid) {
      this.carnum();
      this.countMoney();
      this.getCartList();
      this.gainCount();
    }
  },
  methods: {
    goDesignCon(designItem) {
      _router.push({
        path: '/pages/designer/main',
        query: {
          id: designItem.designerId,
        },
      });
    },
    goGoodsCon(item) {
      _router.push({
        path: '/pages/GoodsCon/GoodsCon',
        query: {
          id: item.productId,
        },
      });
    },
    getCartList: function () {
      let that = this;
      getCartList().then((res) => {
        that.cartList = res.data;
        let checkedIds = cookie.get(CHECKED_IDS) || [];

        console.log('ssssssssssssss', checkedIds);
        if (!Array.isArray(checkedIds)) checkedIds = [];
        let len = 0;
        this.cartList.valid.forEach((cart) => {
          cart.catList.forEach((cat) => {
            if (checkedIds.indexOf(cat.id) !== -1) cat.checked = true;
            len++;
          });
        });
        if (checkedIds.length) {
          that.checkedIds = checkedIds;
          that.isAllSelect = checkedIds.length === len;
          that.carnum();
          that.countMoney();
        }
        this.loaded = true;
      });
    },
    //删除商品；
    delgoods: function () {
      let that = this,
        list = that.cartList.valid,
        id = [];
      list.forEach(function (val) {
        val.catList.forEach(function (val) {
          if (val.checked === true) {
            id.push(val.id);
          }
        });
      });
      // let that = this,
      //   id = [],
      //   valid = [],
      //   list = that.cartList.valid;
      // list.forEach(function (val) {
      //   if (val.checked === true) {
      //     id.push(val.id);
      //   }
      // });
      if (id.length === 0) {
        uni.showToast({
          title: '请选择产品',
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      postCartDel(id).then(function () {
        // list.forEach(function (val, i) {
        //   if (val.checked === false || val.checked === undefined)
        //     valid.push(list[i]);
        // });
        // that.$set(that.cartList, "valid", valid);
        that.carnum();
        that.countMoney();
        that.gainCount();
        that.getCartList();
      });
    },
    // //获取数量
    gainCount: function () {
      let that = this;
      getCartCount().then((res) => {
        that.count = res.data.count;
      });
    },
    //清除失效产品；
    delInvalidGoods: function () {
      let that = this,
        id = [],
        list = that.cartList.invalid;
      list.forEach(function (val) {
        id.push(val.id);
      });
      postCartDel(id).then(function () {
        list.splice(0, list.length);
        that.gainCount();
        that.getCartList();
      });
    },
    //批量收藏;
    collectAll: function () {
      let that = this,
        data = {
          id: [],
          category: '',
        },
        list = that.cartList.valid;
      list.forEach(function (val) {
        if (val.checked === true) {
          data.id.push(val.product_id);
          data.category = val.type;
        }
      });
      if (data.id.length === 0) {
        uni.showToast({
          title: '请选择产品',
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      postCollectAll(data).then(function () {
        uni.showToast({
          title: '收藏成功!',
          icon: 'none',
          duration: 2000,
        });
      });
    },
    //立即下单；
    placeOrder: function () {
      let that = this,
        list = that.cartList.valid,
        id = [];
      list.forEach(function (val) {
        val.catList.forEach(function (val) {
          if (val.checked === true) {
            id.push(val.id);
          }
        });
      });
      // .catList.forEach(function (val) {
      // if (val.checked === true) {
      //   id.push(val.id);
      // }
      // });
      // list.forEach(function (val) {
      //   if (val.checked === true) {
      //     id.push(val.id);
      //   }
      // });
      if (id.length === 0) {
        uni.showToast({
          title: '请选择产品',
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      _router.push({
        path: '/pages/order/orderSubmission/orderSubmission',
        query: {
          id: id.join(','),
        },
      });
    },
    manage: function () {
      let that = this;
      that.footerswitch = !that.footerswitch;
    },
    goodsOpen: function () {
      let that = this;
      that.goodsHidden = !that.goodsHidden;
    },
    //加
    plus: function (designIndex, cartIndex) {
      let that = this;
      let list = that.cartList.valid[designIndex].catList[cartIndex];
      list.cartNum++;
      if (list.attrInfo) {
        if (list.cartNum >= list.attrInfo.stock) {
          that.$set(list, 'cart_num', list.attrInfo.stock);
        }
      } else {
        if (list.cartNum >= list.stock) {
          that.$set(list, 'cart_num', list.stock);
        }
      }
      that.carnum();
      that.countMoney();
      that.syncCartNum(list);
    },
    //减
    reduce: function (designIndex, cartIndex) {
      let that = this;
      let list = that.cartList.valid[designIndex].catList[cartIndex];
      if (list.cartNum <= 1) {
        uni.showToast({
          title: '已经是底线啦!',
          icon: 'none',
          duration: 2000,
        });
        return;
      }
      list.cartNum--;
      if (list.cartNum < 1) {
        that.$set(list, 'cart_num', 1);
      }
      that.carnum();
      that.countMoney();
      that.syncCartNum(list);
    },
    syncCartNum(cart) {
      if (!cart.sync) {
        changeCartNum(cart.id, Math.max(cart.cartNum, 1) || 1)
          .then((res) => {
            this.getCartList();
            this.gainCount();
          })
          .catch((error) => {
            this.gainCount();
            uni.showToast({
              title: error.response.data.msg,
              icon: 'none',
              duration: 2000,
            });
          });
      }
    },
    //单选
    switchSelect: function (designIndex, cartIndex) {
      let that = this,
        cart = that.cartList.valid[designIndex].catList[cartIndex],
        i = this.checkedIds.indexOf(cart.id);
      cart.checked = !cart.checked;

      if (i !== -1) this.checkedIds.splice(i, 1);
      if (cart.checked) {
        this.checkedIds.push(cart.id);
      }
      let len = 0;
      let selectnum = [];
      for (let i = 0; i < that.cartList.valid.length; i++) {
        for (let j = 0; j < that.cartList.valid[i].catList.length; j++) {
          if (that.cartList.valid[i].catList[j].checked) {
            selectnum.push(true);
          }
          len++;
        }
      }
      console.log(len, selectnum.length);
      that.isAllSelect = selectnum.length === len;
      that.$set(that, 'cartList', that.cartList);
      that.$set(that, 'isAllSelect', that.isAllSelect);
      cookie.set(CHECKED_IDS, that.checkedIds);
      that.carnum();
      that.gainCount();
      that.countMoney();
    },
    //全选
    allChecked: function (e) {
      console.log(e);
      let that = this;
      let selectAllStatus = e.detail.value[0] == 'allSelect' ? true : false;
      console.log(selectAllStatus);
      // let selectAllStatus = that.isAllSelect;
      let checkedIds = [];
      // for (let i = 0; i < array.length; i++) {
      //   array[i].checked = selectAllStatus;
      //   checked.push()
      // }
      that.cartList.valid.forEach((cartPar) => {
        cartPar.catList.forEach((cart) => {
          cart.checked = selectAllStatus;
          if (selectAllStatus) {
            checkedIds.push(cart.id);
          }
        });
      });
      let cartList = {
        ...that.cartList,
      };
      that.cartList = [];
      that.cartList = cartList;
      console.log(this.cartList);
      this.$set(this, 'cartList', this.cartList);
      this.$set(this, 'isAllSelect', selectAllStatus);
      this.checkedIds = checkedIds;
      cookie.set(CHECKED_IDS, checkedIds);
      that.carnum();
      that.countMoney();
      this.$forceUpdate();
    },
    //数量
    carnum: function () {
      let that = this;
      var carnum = 0;
      var array = that.cartList.valid;
      let arrDesign = that.cartList.valid;
      for (let p = 0; p < arrDesign.length; p++) {
        const array = arrDesign[p].catList;
        for (let i = 0; i < array.length; i++) {
          if (array[i].checked === true) {
            carnum += parseInt(array[i].cartNum);
          }
        }
        that.$set(that, 'cartCount', carnum);
      }
    },
    //总共价钱；
    countMoney: function () {
      let that = this;
      let carmoney = 0;
      let arrDesign = that.cartList.valid;
      for (let p = 0; p < arrDesign.length; p++) {
        const array = arrDesign[p].catList;
        for (let i = 0; i < array.length; i++) {
          if (array[i].checked === true) {
            carmoney = add(carmoney, mul(array[i].cartNum, array[i].truePrice));
          }
        }
        that.countmoney = carmoney;
      }
    },
  },
};
</script>

<style lang="less">
@import 'style';
.footer-h5 {
  bottom: 50px;
}
.shoppingCart {
  position: relative;
  .list {
    margin-top: 150rpx;
    padding-top: 15rpx;
  }
}

.list {
  display: flex;
  flex-direction: column;
  gap: 18rpx;
  margin: 18rpx !important;
  .item {
    background: #ffffff;
    box-shadow: 0rpx 2rpx 4rpx 2rpx rgba(0, 0, 0, 0.16);
    border-radius: 16rpx 16rpx 16rpx 16rpx;
  }
}
.design-item {
  .design-item-pic {
    display: flex;
    align-items: center;
    gap: 16rpx;
    .deign-pic {
      width: 40rpx;
      height: 40rpx;
      border-radius: 58rpx 58rpx 58rpx 58rpx;
    }
    .desgin-name {
      font-weight: bold;
      font-size: 24rpx;
      color: #222222;
      line-height: 34rpx;
    }
    .right-icon {
      width: 12rpx;
      height: 20rpx;
    }
  }
}

.cart-_item {
  display: flex;
  align-items: center;
  .picTxt {
    padding: 32rpx 0 !important;
    border-bottom: 1rpx solid #e4e4e4 !important;
    .carnum {
      bottom: 39rpx !important;
    }
  }
}
</style>
